package com.example.simple_android.annotation.impl;

import android.text.TextUtils;

import com.example.simple_android.Manager.impl.InjectionManager;
import com.example.simple_android.annotation.Injection;

import java.lang.reflect.Field;
import java.util.Map;

public class InjectionImpl {

    /**
     * 调用此方法，将全局对象中被Injection注解标记的Field自动注入，被自动注入的对象全部存放在InjectionManager中
     */
    public static void injection() {
        Map<String, Object> lookups = InjectionManager.getInstance().lookups();
        for (Object o : lookups.values()) {
            Class<?> aClass = o.getClass();
            Field[] fields = aClass.getDeclaredFields();
            for (Field field : fields) {
                Injection injection = field.getDeclaredAnnotation(Injection.class);
                if (injection == null) {
                    continue;
                }
                String flag = injection.flag();
                field.setAccessible(true);
                Class<?> type = field.getType();
                Object object;
                if (TextUtils.isEmpty(flag)) {
                    object = lookups.get(type.getName());
                } else {
                    object = lookups.get(type.getName().concat(".").concat(flag));
                }
                try {
                    field.set(o, object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 向指定的类中，自动注入被Injection标记的Field
     * @param o 指定的类的对象
     */
    public static void injection(Object o) {
        Class<?> aClass = o.getClass();
        Map<String, Object> lookups = InjectionManager.getInstance().lookups();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            Injection injection = field.getDeclaredAnnotation(Injection.class);
            if (injection == null) {
                continue;
            }
            String flag = injection.flag();
            Class<?> type = field.getType();
            field.setAccessible(true);
            Object object;
            if (TextUtils.isEmpty(flag)) {
                object = lookups.get(type.getName());
            } else {
                object = lookups.get(type.getName().concat(".").concat(flag));
            }
            try {
                field.set(o, object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
